package main;

import java.awt.BorderLayout;
import java.io.*;

import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.net.*;

public class client extends JPanel implements ActionListener {

	private JButton cntButton;
	private JTextField cmdTextField;
	private JButton goButton;
	static final String goBtn = "goAction";
	static final String cntBtn = "cntAction";
	private Connection connection = null;
	static final String database = "ThuVienBaiHat";
	static final String username = "sa";
	static final String password = "password";
	private JTable result;
	private DefaultTableModel model;
	private Vector<String> colVector;
	static final int selectCmd = 0;
	static final int insertCmd = 1;
	static final int updateCmd = 2;
	static final int deleteCmd = 3;
	static String strClient = "";//insert into THONGTIN values('ngo anh khoi','abc','DeathMetal','album','30000')";
	Socket s;
	
	public client() {
		super(new BorderLayout());
		this.setPreferredSize(new Dimension(900, 310));

		JPanel p1 = new JPanel();
		cntButton = new JButton("Connect");
		cntButton.setHorizontalAlignment(SwingConstants.LEFT);
		cntButton.setPreferredSize(new Dimension(100, 100));
		cntButton.setActionCommand(cntBtn);
		p1.add(cntButton);

		JPanel p2 = new JPanel();
		p2.setLayout(new GridLayout(3, 1));

		cmdTextField = new JTextField();
		cmdTextField.setPreferredSize(new Dimension(270, 20));

		goButton = new JButton("Go!");
		goButton.setPreferredSize(new Dimension(150, 30));
		goButton.setActionCommand(goBtn);

		p2.add(cmdTextField);
		p2.add(goButton, -1);

		colVector = new Vector<String>();
		colVector.add("Ten");
		colVector.add("CaSi");
		colVector.add("TheLoai");
		colVector.add("TenAlbum");
		colVector.add("NamPhatHanh");

		result = new JTable();
		model = new DefaultTableModel(colVector, 0);
		result.setModel(model);

		JScrollPane p3 = new JScrollPane(result);
		p3.setPreferredSize(new Dimension(500, 300));

		JPanel p4 = new JPanel();
		p4.add(p1);
		p4.add(p2);
		p4.add(p3);

		goButton.addActionListener(this);
		cntButton.addActionListener(this);

		this.add(p4);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if (goBtn == e.getActionCommand()) 
		{
			
			strClient = cmdTextField.getText();
			JOptionPane.showMessageDialog(new JFrame(),
					strClient, "Cau lenh SQL",
					JOptionPane.ERROR_MESSAGE);
			try {
				sendMsg(strClient);
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			/*
			 * if (connection == null) { JOptionPane.showMessageDialog(new
			 * JFrame(), "Chua ket noi voi may chu!", "Error Message",
			 * JOptionPane.ERROR_MESSAGE); return; } else if
			 * (cmdTextField.getText().isEmpty()) {
			 * JOptionPane.showMessageDialog(new JFrame(), "Lenh SQL Rong!",
			 * "SQL String", JOptionPane.ERROR_MESSAGE); return; } else { // if
			 * connected and SQL string not empty String sqlCommand =
			 * cmdTextField.getText(); Statement stmt; model = new
			 * DefaultTableModel(colVector, 0); try { stmt =
			 * connection.createStatement(); if (sqlCmdClassifier(sqlCommand) ==
			 * selectCmd) { ResultSet rs = stmt.executeQuery(sqlCommand);
			 * processSelectCmd(rs); } else { int rs =
			 * stmt.executeUpdate(sqlCommand); if (rs == 0) {
			 * JOptionPane.showMessageDialog(new JFrame(),
			 * "Khong co thay doi nao trong CSDL", "Thong bao",
			 * JOptionPane.ERROR_MESSAGE); } else {
			 * JOptionPane.showMessageDialog(new JFrame(), "Da cap nhat CSDL",
			 * "Thong bao", JOptionPane.ERROR_MESSAGE); } } stmt.close(); }
			 * catch (SQLException e1) { // TODO Auto-generated catch block
			 * e1.printStackTrace(); JOptionPane.showMessageDialog(new JFrame(),
			 * "Nhap sai cau lenh SQL!", "Loi cau lenh SQL",
			 * JOptionPane.ERROR_MESSAGE); } }
			 */
		} // end if goBtn
		else if (cntBtn == e.getActionCommand()) {
			System.out.print("connecting...\n");
		//	ketnoi();
			connect k = new connect();
			k.start();
		}
	}

	public void ketnoi() {
		try {
			s = new Socket("localhost", 1234);

			InputStream is = s.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			
			OutputStream os = s.getOutputStream();
			BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));

			String sentMessage = "";
			String receivedMessage;

			System.out.println("Talking to Server");

			do {
				// sent data to server.
				// system.in
				//DataInputStream din = new DataInputStream(System.in);
				sentMessage = strClient;//din.readLine();
				bw.write(sentMessage);
				bw.newLine();
				bw.flush();

				// if client sent key "quit" server is going to disconnect
				if (sentMessage.equalsIgnoreCase("quit"))
					break;
				// show result to client's JTable
				else {
					receivedMessage = br.readLine();
					System.out.println("Received : " + receivedMessage);
				}

			} while (true);
			bw.close();
			br.close();
			s.close();
		} catch (IOException e) {
			System.out.println("There're some error");
		}
	}
	
	public void sendMsg(String strMsg) throws IOException
	{
		try {
			Socket s = new Socket("localhost", 1234);

			InputStream is = s.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is));

			OutputStream os = s.getOutputStream();
			BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));

			String sentMessage = "";
			String receivedMessage;

			System.out.println("Talking to Server");

			do {
				// Sent data to server. 
				// system.in
				//DataInputStream din = new DataInputStream(System.in);
				sentMessage = strMsg;//din.readLine();
				bw.write(sentMessage);
				bw.newLine();
				bw.flush();

				// if client sent key is "quit" , server is going to disconnect
				if (sentMessage.equalsIgnoreCase("quit"))
					break;
				// show result to client's JTable
				else {
					receivedMessage = br.readLine();
					System.out.println("Received : " + receivedMessage);
				}

			} while (true);
			bw.close();
			br.close();
			s.close();
		} catch (IOException e) {
			System.out.println("There're some error");
		}
	}

	private void processSelectCmd(ResultSet rs) {
		try {
			ResultSetMetaData rsmd = rs.getMetaData();
			int colNo = rsmd.getColumnCount();

			while (rs.next()) {
				Object[] objects = new Object[colNo];
				for (int i = 0; i < colNo; i++) {
					objects[i] = rs.getObject(i + 1);
				}
				model.addRow(objects);
				model.addRow(objects);
				model.addRow(objects);
				model.addRow(objects);
				model.addRow(objects);
				model.addRow(objects);
				model.addRow(objects);
				model.addRow(objects);
				model.addRow(objects);
				model.addRow(objects);
				model.addRow(objects);
				model.addRow(objects);
				model.addRow(objects);
				model.addRow(objects);
			}
			result.setModel(model);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private int sqlCmdClassifier(String s) {
		String s0 = s.trim();
		s0 = s0.toLowerCase();
		String[] temp = s0.split(" ");
		switch (temp[0]) {
		case "select":
			return selectCmd;
		case "insert":
			return insertCmd;
		case "update":
			return updateCmd;
		case "delete":
			return deleteCmd;
		default:
			return -1;
		}
	}

	public static void main(String[] args) {

		JFrame.setDefaultLookAndFeelDecorated(true);

		// Create and set up the window.
		JFrame frame = new JFrame("Client");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		// Create and set up the content pane.
		JComponent newContentPane = new client();

		newContentPane.setOpaque(true); // content panes must be opaque
		frame.setContentPane(newContentPane);

		// Display the window.
		frame.pack();
		frame.setVisible(true);
	}
}

class connect extends Thread{
	public void run(){
		try {
			Socket s = new Socket("localhost", 1234);
		} catch (IOException e) {
			System.out.println("There're some error");
		}
	}
}
